package com.czk.yygh.user.controller.api;

import com.alibaba.fastjson.JSONObject;
import com.czk.model.user.UserInfo;
import com.czk.yygh.common.helper.JwtHelper;
import com.czk.yygh.common.result.Result;
import com.czk.yygh.user.service.UserInfoService;
import com.czk.yygh.user.utils.ConstantWxPropertiesUtil;
import com.czk.yygh.user.utils.HttpClientUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/11/23 21:18
 */
@Controller
@RequestMapping("/api/ucenter/wx")
@Api(tags = "微信登录管理")
public class WeixinApiController {
    @Autowired
    private UserInfoService userInfoService;
    @GetMapping("/getLoginParam")
    @ResponseBody
    @ApiOperation(value = "生成二维码内容")
    public Result getQrContent() {
        Map<String, Object> map = new HashMap<>();
        try {
            map.put("appid", ConstantWxPropertiesUtil.WX_OPEN_APP_ID);
            map.put("scope", "snsapi_login");
            String wxOpenRedirectUrl = ConstantWxPropertiesUtil.WX_OPEN_REDIRECT_URL;
            // 编码
            wxOpenRedirectUrl = URLEncoder.encode(wxOpenRedirectUrl, "utf-8");
            map.put("redirect_uri", wxOpenRedirectUrl);
            map.put("state", System.currentTimeMillis() + "");
            return Result.ok(map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 微信登录回调地址
     *
     * @param code  微信携带
     * @param state 微信重定向携带
     * @return
     */
    @GetMapping("/callback")
    public String callback(String code, String state) {
        System.out.println("code= " + code);
        System.out.println("state= " + state);
        // 拿着code和微信id和秘钥，请求微信固定地址 ，得到两个值
        // 使用code和appid以及appscrect换取access_token
        // 拼接token的url地址 %s占位符
        StringBuffer baseAccessTokenUrl = new StringBuffer()
                .append("https://api.weixin.qq.com/sns/oauth2/access_token")
                .append("?appid=%s")
                .append("&secret=%s")
                .append("&code=%s")
                .append("&grant_type=authorization_code");
        // 替换占位符
        String accessTokenUrl = String.format(baseAccessTokenUrl.toString(),
                ConstantWxPropertiesUtil.WX_OPEN_APP_ID,
                ConstantWxPropertiesUtil.WX_OPEN_APP_SECRET,
                code);
        // 获取token
        try {
            String accesstokenInfo = HttpClientUtil.get(accessTokenUrl);
            // 解析为json
            JSONObject jsonObject = JSONObject.parseObject(accesstokenInfo);
            // 拿到token
            String access_token = jsonObject.getString("access_token");
            System.out.println("access_token= " + access_token);
            // 微信用户的唯一标识
            String openid = jsonObject.getString("openid");
            System.out.println("openid= " + openid);
            // g根据openid判断以前是否登陆过
            UserInfo userInfo = userInfoService.selectWxInfoOpenId(openid);
            if (userInfo==null){
                // 保存信息
                // 获取请求人的信息
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";
                String userInfoUrl = String.format(baseUserInfoUrl, access_token, openid);
                // 拿到用户信息
                String resultInfo = HttpClientUtil.get(userInfoUrl);
                System.out.println("resultInfo:"+resultInfo);
                // 拿到用户json
                JSONObject resultUserInfoJson = JSONObject.parseObject(resultInfo);
                // 哟用户昵称
                String nickname = resultUserInfoJson.getString("nickname");
                // 用户头像
                String headimgurl = resultUserInfoJson.getString("headimgurl");
                userInfo=new UserInfo();
                userInfo.setNickName(nickname);
                userInfo.setOpenid(openid);
                userInfo.setStatus(1);
                // 保存用户
                userInfoService.save(userInfo);
            }
            //返回name和token字符串
            Map<String,String> map = new HashMap<>();
            String name = userInfo.getName();
            if(StringUtils.isEmpty(name)) {
                name = userInfo.getNickName();
            }
            if(StringUtils.isEmpty(name)) {
                name = userInfo.getPhone();
            }
            map.put("name", name);

            // 判断userInfo是否有手机号，如果手机号为空，返回openid
            // 如果手机号不为空，返回openid值是空字符串
            // 前端判断：如果openid不为空，绑定手机号，如果openid为空，不需要绑定手机号
            if(StringUtils.isEmpty(userInfo.getPhone())) {
                map.put("openid", userInfo.getOpenid());
            } else {
                map.put("openid", "");
            }
            // 使用jwt生成token字符串
            String token = JwtHelper.createToken(userInfo.getId(), name);
            map.put("token", token);
            // 跳转到前端页面
            return "redirect:" + ConstantWxPropertiesUtil.YYGH_BASE_URL + "/weixin/callback?token="+map.get("token")+ "&openid="+map.get("openid")+"&name="+URLEncoder.encode(map.get("name"),"utf-8");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }
}
